<script setup>
import { defineComponent, ref, toRefs } from "vue";

const CustomRender = defineComponent({
  props: {
    render: {
      type: Function,
      required: true,
    },
  },
  render() {
    return this.render();
  },
});

const props = defineProps({
  dialogParams: {
    type: Object,
    default: () => ({}),
  },
  options: {
    type: Object,
    default: () => ({}),
  },
  formItem: {
    type: Array,
    default: () => [],
  },
  formData: {
    type: Object,
    default: () => ({}),
  },
});

const { formData } = toRefs(props);

const formRef = ref(null);

const emit = defineEmits(["close", "confirm"]);

function handleClose() {
  formRef.value.resetFields();
  emit("close");
}

function handleConfirm() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    emit("confirm");
  });
}
</script>

<template>
  <el-dialog
    :model-value="dialogParams.visible"
    :width="options.dialogWidth"
    :close-on-click-modal="false"
    :show-close="false"
    :title="dialogParams.title"
  >
    <el-form
      ref="formRef"
      :label-width="options.labelWidth"
      :model="formData"
      label-suffix=" : "
    >
      <template v-for="item in formItem" :key="item.prop">
        <el-form-item
          v-if="!item.hide"
          :label="item.label"
          :prop="item.prop"
          :rules="item.rules"
        >
          <template v-if="item.customRender">
            <CustomRender
              v-model="formData[item.prop]"
              :render="item.customRender"
            ></CustomRender>
          </template>
          <template v-else>
            <el-input v-model="formData[item.prop]" clearable></el-input>
          </template>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button @click="handleClose"> 取消 </el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
